from datetime import datetime

from django.db import transaction
from ability.enums import ErrorCode
from ability.format import CustomResponse
from ability.models import Attach, Experiment, Paper, Report, StudentExperiment
from rest_framework.views import APIView
import ability.permissions as pm
from ability.excepts import LogicException
from rest_framework.response import Response
import traceback


class ReportCreateView(APIView):

  queryset = Experiment.objects.all()
  permission_classes = [pm.AllowAny]

  def __init__(self, **kwargs):
    print('PcVNCView init')
    self.response_format = CustomResponse().response
    super(ReportCreateView, self).__init__(**kwargs)

  def initial(self, request, *args, **kwargs):
    """
    Runs anything that needs to occur prior to calling the method handler.
    """
    self.format_kwarg = self.get_format_suffix(**kwargs)

    # Perform content negotiation and store the accepted info on the request
    neg = self.perform_content_negotiation(request)
    request.accepted_renderer, request.accepted_media_type = neg

    # Determine the API version, if versioning is in use.
    version, scheme = self.determine_version(request, *args, **kwargs)
    request.version, request.versioning_scheme = version, scheme

    # Ensure that the incoming request is permitted
    try:
        print('before perform_authentication')
        print(request.user)
        self.perform_authentication(request)
        print('before check_permissions')
        self.check_permissions(request)
        print('before check_throttles')
        self.check_throttles(request)
        print('after check_throttles')
    except Exception as e:
    	#traceback.print_exc()
      print(str(e))

  def post(self, request, *args, **kwargs):
    
    try:
      print(request.META, request.data)
      experiment = StudentExperiment.objects.get(experiment_id=request.data['id'], vnccode=request.data['vnccode'])

      if experiment is None:
        raise LogicException('错误的请求')

      if experiment.experiment.status != 'N':
        raise LogicException('该实验已经结束')

      with transaction.atomic():

        report = Report.objects.filter(student=experiment.student, experiment=experiment.experiment).first()
        if report:
          raise LogicException("报告已提交")

        report = Report()
        report.title = self.request.data['title']
        report.content = self.request.data['content']
        report.experiment = experiment.experiment
        report.student = experiment.student
        report.submit_time = datetime.now()
        report.save()
        attaches = self.request.data['attaches']
        for attach in attaches:
            attach_obj = Attach()
            attach_obj.report = report
            attach_obj.file_type = 'D'
            attach_obj.location = attach
            attach_obj.file_name = attach
            attach_obj.save()

        imgs = self.request.data['imgs']
        for attach in imgs:
            attach_obj = Attach()
            attach_obj.report = report
            attach_obj.file_type = 'I'
            attach_obj.location = attach
            attach_obj.file_name = attach
            attach_obj.save()
        
        videos = self.request.data['videos']

        for attach in videos:
            attach_obj = Attach()
            attach_obj.report = report
            attach_obj.file_type = 'V'
            attach_obj.location = attach
            attach_obj.file_name = attach
            attach_obj.save()

      self.response_format['data'] = {} 
      return Response(self.response_format)
    except StudentExperiment.DoesNotExist:
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = "数据不存在"
      return Response(self.response_format)
    except LogicException as e:
      traceback.print_exc()
      print(str(e))
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = str(e)
      return Response(self.response_format)
    except Exception as e:
      traceback.print_exc()
      print(str(e))
      self.response_format["error_code"] = ErrorCode.parameter_error.value
      self.response_format["message"] = str(e)
      return Response(self.response_format)
